{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<h1>EMA Crossover Strategy</h1>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import fxcmpy\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "import datetime as dt\n",
    "\n",
    "# Importing the EMA indicator\n",
    "from pyti.exponential_moving_average import exponential_moving_average as ema\n",
    "\n",
    "# Allows for printing the whole data frame\n",
    "pd.set_option('display.max_columns', None)\n",
    "pd.set_option('display.max_rows', None)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<h3>Connecting and Retrieving Prices</h3>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "con = fxcmpy.fxcmpy(config_file='fxcm.cfg')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# retrieve daily candles for the GBP/JPY currency pair from 01/01/2016 until 06/10/2018\n",
    "\n",
    "df = con.get_candles('GBP/JPY', period='D1',start= dt.datetime(2016, 1, 1),end = dt.datetime(2018, 6, 10))\n",
    "\n",
    "#df = pd.read_csv('historical_data.csv', index_col = 0, parse_dates=True)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<h3>Define the EMA Strategy</h3>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "# Define our pip cost and lot size\n",
    "pip_cost = .0911\n",
    "lot_size = 10\n",
    "\n",
    "# Define our EMA Fast / Slow parameters\n",
    "ema_fast = 12\n",
    "ema_slow = 20\n",
    "\n",
    "# Populate our dataframe with fast and slow EMA figures\n",
    "df['mva_fast'] = ema(df['askclose'], ema_fast)\n",
    "df['mva_slow'] = ema(df['askclose'], ema_slow)\n",
    "\n",
    "# When the EMA fast crosses the EMA slow, a buy signal is triggered\n",
    "df['signal'] = np.where(df['mva_fast'] > df['mva_slow'],1,0)\n",
    "df['position'] = df['signal'].diff()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "# Check on the dataframe to see the newly created columns\n",
    "\n",
    "df"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "<h3>A Simple Backtest</h3>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "begin_prices = []\n",
    "end_prices = []\n",
    "profits = 0\n",
    "\n",
    "# Finding when a position is initiated and getting the open / close prices for the position\n",
    "for i, row in df.iterrows():\n",
    "    if row['position'] == 1:\n",
    "        begin_prices.append(float(row['askopen']))\n",
    "    if row['position'] == -1:\n",
    "        end_prices.append(float(row['askopen']))\n",
    "\n",
    "# Calculating the profit / loss using our pip cost and lot size\n",
    "for i in range(len(begin_prices)):\n",
    "    profit = (end_prices[i] - begin_prices[i]) * 100 * pip_cost * lot_size\n",
    "    profits += profit\n",
    "    print(\"The return for trade \" + str(i + 1) + \" is: \" + str(int(profit)))\n",
    "    \n",
    "print(\"The return for the period is: \" + str(int(profits)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "<h3>A Better Backtest</h3>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Profit / loss figures are good, but they don't tell the whole story\n",
    "# It's better to see what happens with the positions while they're open, as well\n",
    "\n",
    "returns = 0\n",
    "\n",
    "# Gets the number of pips that the market moved during the day\n",
    "df['difference (pips)'] = (df['askclose'] - df['askopen']) * 100\n",
    "#df['p/l'] = df['difference'] * pip_cost * lot_size\n",
    "\n",
    "# Calculates the daily return while a position is active\n",
    "# 'Total' column records our running profit / loss for the strategy\n",
    "for i, row in data.iterrows():\n",
    "    if CountPL==True:\n",
    "      returns += (row['difference (pips)'] * pip_cost * lot_size)\n",
    "      data.loc[i,'total'] = returns\n",
    "    else:\n",
    "      data.loc[i,'total'] = returns\n",
    "    if row['signal'] == 1:\n",
    "      CountPL=True\n",
    "    else:\n",
    "      CountPL=False "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Check on the dataframe to see our newly created columns\n",
    "\n",
    "df"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<h3>Visualizing Trading Signals</h3>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "%matplotlib inline\n",
    "\n",
    "fig = plt.figure(figsize=(12,8))\n",
    "ax1 = fig.add_subplot(111,  ylabel='GBP/JPY Price')\n",
    "\n",
    "# Plotting market prices and moving averages\n",
    "df['askclose'].plot(ax=ax1, color='r', lw=1.)\n",
    "df[['mva_fast', 'mva_slow']].plot(ax=ax1, lw=2.)\n",
    "\n",
    "# Placing markers for our position entry\n",
    "ax1.plot(df.loc[df.position == 1.0].index, \n",
    "         df.mva_fast[df.position == 1.0],\n",
    "         '^', markersize=10, color='m')\n",
    "\n",
    "# Placing markers for our position exit\n",
    "ax1.plot(df.loc[df.position == -1.0].index, \n",
    "         df.mva_slow[df.position == -1.0],\n",
    "         'v', markersize=10, color='k')\n",
    "\n",
    "# Plotting our returns\n",
    "#ax2 = ax1.twinx()\n",
    "#ax2.grid(False)\n",
    "#ax2.set_ylabel('Profits in $')\n",
    "#ax2.plot(df['total'], color = 'green')\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<h3>Visualizing Returns</h3>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "fig = plt.figure(figsize=(12,8))\n",
    "ax1 = fig.add_subplot(111,  ylabel='Profits in $')\n",
    "\n",
    "# Plotting our returns\n",
    "df['total'].plot(ax=ax1, color='r', lw=1.)\n",
    "\n",
    "# Placing markers for our position entry\n",
    "ax1.plot(df.loc[df.position == 1.0].index, \n",
    "         df.total[df.position == 1.0],\n",
    "         '^', markersize=10, color='m')\n",
    "\n",
    "# Placing markers for our position exit\n",
    "ax1.plot(df.loc[df.position == -1.0].index, \n",
    "         df.total[df.position == -1.0],\n",
    "         'v', markersize=10, color='k')\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
